import { GameMode } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent, ValidGamePlayer } from "@sapi-game/main";
import { RandomUtils } from "@sapi-game/utils";
import { KcqdMainState } from "../mainState";
import { KcqdPlayer } from "../module";

export class KcqdProcessController extends GameComponent<KcqdMainState> {
    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        this.subscribe(
            timer.events.onTime,
            () => {
                this.win();
                this.nextRound();
            },
            {
                time: 0,
                once: false,
            }
        );
    }

    nextRound() {
        //延迟一段时间下一轮
        this.runner.runDelay(() => {
            const timer = this.state.getComponent(Timer);
            timer.set(this.context.config.roundTime);
            timer.start();
            const result = this.getSausage();
            //如果没抽到就结束
            if (!result) {
                this.state.end();
            }
        }, 40);
    }

    win() {
        const players = this.state.getPlayersWithSauage();
        if (players.length) {
            this.context.players.sendMessage(
                `§a§l${players.map((p) => p.name).join(",")} §6§l在本回合获胜`
            );
            players.forEach((p) => {
                p.isSausage = false;
                p.win = true;
                p.player?.setGameMode(GameMode.Spectator);
                p.clear();
            });
        } else {
            this.context.players.sendMessage("本回合没有人获胜");
        }
    }

    /**给随机玩家烤肠 */
    getSausage() {
        this.context.players.getAll().forEach((p) => {
            p.isSausage = false;
        });
        const players = this.context.players.filter(
            (p) => p.isValid && !p.win
        ) as ValidGamePlayer<KcqdPlayer>[];
        const player = RandomUtils.choice(players);
        if (!player || players.length == 1) {
            return false;
        }
        player.isSausage = true;
        this.state.giveSausage(player.player);
        this.context.players.sendMessage(`§e${player.name} §6§l获得了烤肠`);
        return true;
    }
}
